package com.shuwen.cdp.track.controller;

import com.alibaba.fastjson.JSONObject;
import com.shuwen.cdp.track.service.ProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/track")
public class LogBackController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Logger track_logger = LoggerFactory.getLogger("trackLogger");

    @Resource
    private ProducerService producerService;


    @RequestMapping(value = "/sa.gif", method = RequestMethod.GET)
    @ResponseBody
    public void track(@RequestParam(value = "data",required = false) String data,
                          @RequestParam(value = "project",required = false) String project,
                          HttpServletRequest request) {
        try{
            String ip = request.getRemoteAddr();
            BASE64Decoder decoder = new BASE64Decoder();
            data = new String(decoder.decodeBuffer(data), "UTF-8");
            //本地文件记录用户行为日志
            track_logger.info(ip+"^"+data+"^"+project);
            //转成json格式，用于kafka发送
            JSONObject returnData = JSONObject.parseObject(data);
            returnData.put("project",project);
            returnData.put("ip",ip);
            returnData.put("server_time",System.currentTimeMillis());
            data = returnData.toString();
            producerService.sendMessage(data);
        }catch (Exception e){
            logger.error("track log error:"+e.getMessage());
        }

    }

}